package Aleehot100;

import java.util.Arrays;

/**
 * ClassName: c065
 * Package: Aleehot100
 * Description: 34. 在排序数组中查找元素的第一个和最后一个位置
 *
 * @Author BCXJ
 * @Create 2025/8/15 08:35
 * @Version 1.0
 * @Since 1.0
 */
public class c065 {
    public static void main(String[] args) {
        int[] arr = {5,7,7,8,8,10};
        System.out.println(Arrays.toString(searchRange(arr, 8)));
    }

    public static int[] searchRange(int[] nums, int target) {
        // 两次二分
        // 第一次二分，找到最右的位置
        int resLeft = -1, resRight = -1;
        int l = 0, r = nums.length - 1, mid = 0;
        while(l <= r) {
            mid = l + ((r - l) >> 1);
            if(nums[mid] <= target) {
                l = mid + 1;
            } else {
                r = mid - 1;
            }
            if(nums[mid] == target) {
                resRight = mid;
            }
        }
        // 第二次二分，找到最左的位置
        l = 0;r = nums.length - 1; mid = 0;
        while(l <= r) {
            mid = l + ((r - l) >> 1);
            if(nums[mid] >= target) {
                r = mid - 1;
            } else {
                l = mid + 1;
            }
            if(nums[mid] == target) {
                resLeft = mid;
            }
        }
        return new int[]{resLeft, resRight};
    }

}
